<?php 	
/**
 * 自由购模块
 */  
define('QR_IMG_URL', 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=');
class freebuy {
	public function getView($param){
		
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $oid=$param->oid;
	    Session::switchCustomer(0);
	    $OrderModel = M("module_product_order");
		$DetailModel = M("module_product_order_detail");
		$RecordModel=M("module_freebuy_record");	
		Session::switchCustomer($customerId);
		$result=$OrderModel->alias("a")
		->join("wx_".$customerId."_user_weixin_info b on a.fromUserName=b.openid")
		->field("a.*,b.nickname,b.headimgurl")
		->where("a.id=$oid")->find();
		if($result["fromUserName"]==$userName) {
			$result["isMe"]=1;
		}
		if(!$result) {
			Output::instance()->resultCode("订单不存在");
			return;
		}
		$price=self::getOrderDetailPrice($oid);
		$deposit=$result["price"];
		$refueMoney=$result["refueMoney"];
		//需要补齐的金额
		$chPrice=$price-$deposit-$refueMoney;
		$friendCount=$RecordModel->alias("a")
		->join("wx_".$customerId."_user_weixin_info b on a.fromUserName=b.openid")
		->field("a.id,a.oid,b.nickname,b.headimgurl")
		->where("a.oid=$oid and a.deleted=0")
		->count();

		$productList=$DetailModel->alias("a")
		->join("inner join wx_module_product b on a.pid=b.id")
		->field("b.name,b.picUrl,b.freeBuyMoney,b.title,b.recommend")
		->where("a.oid=$oid")
		->find();
		$Guid = new Guid();
		$guid = $Guid->toString();
		$result['guid']=$guid;
		$result["productList"]=$productList;
		$result["oid"]=$oid;
		$result["friendCount"]=$friendCount;
		$result["chPrice"]=round($chPrice,2);
		$result["getCount"]=ceil(round($chPrice,2));
		$result["needPrice"]=$price-$deposit;
		$result["baseMoney"]=C("BASEMONEY");
    	Output::instance()->module('freebuy',"view")->object($result);
	}
	public function getFriend($param) {
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $oid=$param->oid;
	    Session::switchCustomer(0);
	    $OrderModel = M("module_product_order");
		$DetailModel = M("module_product_order_detail");
		$RecordModel=M("module_freebuy_record");	
		Session::switchCustomer($customerId);

		$result=$OrderModel->alias("a")
		->join("wx_".$customerId."_user_weixin_info b on a.fromUserName=b.openid")
		->field("a.*,b.nickname,b.headimgurl")
		->where("a.id=$oid")->find();

		if(!$result) {
			Output::instance()->resultCode("订单不存在");
			return;
		}
		$friendList=$RecordModel->alias("a")
		->join("wx_".$customerId."_user_weixin_info b on a.fromUserName=b.openid")
		->field("a.id,a.oid,b.nickname,b.headimgurl,date_format(a.createTime,'%Y-%m-%d %H:%i') as createTime")
		->where("a.oid=$oid and a.deleted=0")
		->order("a.id desc")
		->select();

		$productList=$DetailModel->alias("a")
		->join("inner join wx_module_product b on a.pid=b.id")
		->field("b.name,b.picUrl,b.freeBuyMoney")
		->where("a.oid=$oid")
		->find();

		$result["productList"]=$productList;
		$Guid = new Guid();
		$guid = $Guid->toString();
		$result['guid']=$guid;
		$result["oid"]=$oid;
		$result["friendList"]=$friendList;
		$result["friendCount"]=count($friendList);
		Output::instance()->module('freebuy',"friend")->object($result);
	}
	/**
	 * [supplementAmount 补差价购买回调]
	 * @param  [type] $oid [description]
	 * @return [type]      [description]
	 */
	public function supplementAmount($param) {
		$userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $oid=$param->id;
	    Session::switchCustomer(0);
		$OrderModel = M("module_product_order");
		Session::switchCustomer($customerId);
		$newOrder=$OrderModel->where("moduleId=$oid and status='delivering'")->find();
		if($newOrder) {
			$money=$param->price;
			$success=$OrderModel->query("update wx_module_product_order set status='delivering' where id=$oid");
			if($success!==false) {
				//发模板消息
				if($newOrder["status"]=="paypart") {
					self::SendorderNotice($oid);
				}
				Output::instance()->object(code_success);
			}
		}
	}
	/**
	 * [refundOrder 放弃购买退订金]
	 * @param  [type] $oid [description]
	 * @return [type]      [description]
	 */
	public function refundOrder($oid) {
		$userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    Session::switchCustomer(0);
		$OrderModel = M("module_product_order");
		Session::switchCustomer($customerId);
		$newOrder=$OrderModel->where("id=$oid")->find();
		if(!$newOrder){
			Output::instance()->resultCode(1,"退款订单不存在！");
			return;
		}
		if($newOrder["status"]!="paypart"){
			Output::instance()->resultCode(1,"不可退款的订单状态");
			return;
		}
		$refundMoney=$newOrder["price"];
		$out=R('Product/orderRefund', array($oid,$refundMoney));
	}
	public function getQrCode($param){
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $oid=$param->oid;
	    Session::switchCustomer(0);
		$DetailModel = M("module_product_order_detail");
		$OrderModel = M("module_product_order");
		$QrModel=M("qrcode");	
		Session::switchCustomer($customerId);
		$QrInfo=$QrModel->where("module='freebuy' and moduleId=$oid")->find();
		if(!$QrInfo) {
			$data=QRCode::add(
				"由我定价推广二维码",
				"QRCODE_$oid",
				"freebuy",$oid,"addOrderRefue",
				"QR_LIMIT_STR_SCENE"
			);
			$qrImg=$data["img"];
		} else {
			$qrImg=QR_IMG_URL . $QrInfo["ticket"];
		}
		$result=$OrderModel->alias("a")
		->join("wx_".$customerId."_user_weixin_info b on a.fromUserName=b.openid")
		->field("a.*,b.nickname,b.headimgurl")
		->where("a.id=$oid")->find();
		if($result["fromUserName"]==$userName) {
			$result["isme"]=1;
		}
		$productList=$DetailModel->alias("a")
		->join("inner join wx_module_product b on a.pid=b.id")
		->field("b.name,b.picUrl,b.freeBuyMoney,b.fixedPrice,b.discountedPrice,b.recommend,b.title,b.description")
		->where("a.oid=$oid")
		->find();

		$productList["freeBuyMoney"]=explode(",",$productList["freeBuyMoney"]);
		$Guid = new Guid();
		$guid = $Guid->toString();
		$result['guid']=$guid;
		$result["oid"]=$oid;
		$result["qrImg"]=$qrImg;
		$result["productList"]=$productList;
		$result["baseMoney"]=C("BASEMONEY");
    	Output::instance()->module('freebuy',"detail")->object($result);
	}
	private function getOrderDetailPrice($oid){
		$customerId = Session::$user['customerId'];
		$DetailModel = M("module_product_order_detail");
		$OrderModel = M("module_product_order");
		$details=$DetailModel->where("oid=$oid")->select();
		$order=$OrderModel->where("id=$oid")->find();
		Session::switchCustomer($customerId);
		$sum=0;

		foreach ($details as $key => $value) {
			$sum+=$value["price"]*$value["count"];
		}
		if($order && $order["logisticsCost"]) {
			$sum+=$order["logisticsCost"];
		}
		return $sum;
	}
	/**
	 * [addOrderRefue 扫描二维码更新订单]
	 * @param [type] $param [description]
	 */
	public function addOrderRefue($param){
		$customerId = Session::$user['customerId'];
		$WeixinUserModel=M("_user_weixin_info");
		$userModel=M("_user");
	    Session::switchCustomer(0);
		$OrderModel=M("module_product_order");
		$RecordModel=M("module_freebuy_record");
		$DetailModel = M("module_product_order_detail");
		Session::switchCustomer($customerId);
		$materialModel = M("material");
		$message=$param->message;
		$fromUserName=$message->fromUserName;
		$oid=$param->id;
		$refu=C("BASEMONEY");
		$userInfo=$WeixinUserModel->where("openid='$fromUserName'")->find();
		if($userInfo) {
			$myNickName=$userInfo["nickname"];
		}
		$isExist=$RecordModel->where("fromUserName='$fromUserName' and deleted=0")->find();
		$order=$OrderModel->alias("a")
		->join("wx_".$customerId."_user_weixin_info u on u.openid=a.fromUserName")
		->field("a.*,u.nickname")
		->where("a.id=$oid")->find();

		if($order) {
			$productList=$DetailModel->alias("a")
			->join("inner join wx_module_product b on a.pid=b.id")
			->field("b.name,b.freeBuyMaterialId")
			->where("oid=$oid")->select();
			if(count($productList) >0 ) {
				$proname=$productList[0]["name"];
				$materialId = $productList[0]["freeBuyMaterialId"];
				$materialInfo = $materialModel->where("id=".$materialId)->find();
				$xml = (string)$materialInfo["xml"];
				$xml = str_replace("{{myname}}",$myNickName,$xml);
				$xml = str_replace("{{purchase}}",$order["nickname"],$xml);
				$xml = str_replace("{{product}}",$proname,$xml);
				$xml = simplexml_load_string($xml,'SimpleXMLElement', LIBXML_NOCDATA);
				$item = $xml->Articles->item;
				$articles=array();
				foreach($item as $key=>$value){
					$article=new stdClass();
					$article->title = urlencode((string)$value->title);
					$article->url = urlencode((string)$value->url);
					$article->picurl = urlencode((string)$value->picUrl);
					$article->description = urlencode((string)$value->description);
					array_push($articles, $article);
				}
				$toUser = $fromUserName;
				WeixinApi::sendServiceMsg($toUser, 'news','',$articles);
			}
		}
		if($order["fromUserName"]==$fromUserName) { //排除自己和曾经关注过的
			return;
		}
		$isExistUser=$userModel->where("userName='$fromUserName'")->find();

		if(!$isExistUser) {
			return;
		}
		$subscribeTime=strtotime($isExistUser["subscribeTime"]);
		if(time()-$subscribeTime >= 50) {
			return;
		}
		if(!$isExist || count($isExist) <1 ){ //已经存在
			$OrderModel->startTrans();

			$updateOrderStatus=$OrderModel->where("id=$oid")->setInc("refueMoney",$refu);
			if($updateOrderStatus===false) {
				Log::write("关注订单失败结果".$OrderModel->getlastsql().$updateOrderStatus);
			}
			
			//添加邀请记录
			$data=array(
				"fromUserName"=>$fromUserName,
				"oid"=>$oid,
				"refu"=>$refu,
				"createTime"=>date("Y-m-d H:i:s"),
				"deleted"=>0
		    );
		    $addStatus=$RecordModel->add($data);
		    if($addStatus!==false && $updateOrderStatus!==false) {
				$OrderModel->commit();
			} else {
				Log::write("失败回滚".$OrderModel->getlastsql().$RecordModel->getlastsql());
				$OrderModel->rollback();
			}

			
			//判断订单是否已经完成
			$order=$OrderModel->where("id=$oid")->find();
			if($order && $order["status"]=="paypart") {
				$price=self::getOrderDetailPrice($oid);
				$freePrice=$order["price"]+$order["refueMoney"];
				if($freePrice>=$price) { //订单金额已经完成
					$updateOrderStatus=$OrderModel->query("update wx_module_product_order set status='".order_status_delivering."' where id=$oid");
					if($updateOrderStatus!==false) {
						//发模板消息
						self::SendorderNotice($oid);
					}
				}
			}
		}
	}
	public static function SendorderNotice($oid){
		$cid = Session::$user["customerId"];
		$TemplateModel = M("template_messages");
		Session::switchCustomer(0);
		$OrderModel = M("module_product_order");
		$DetailModel = M("module_product_order_detail");
		Session::switchCustomer($cid);
		$where['a.id'] = $oid;
		$order = $OrderModel->alias("a")
		->join("inner join wx_".$cid."_user_weixin_info b on a.fromUserName=b.openid")
		->field("a.*,b.nickname")
		->where($where)->find();

	    $detail=$DetailModel->alias("a")
	    ->join("wx_module_product b on a.pid=b.id")
	    ->field("group_concat(b.name) as pnames,sum(a.price*a.count) as amount")
	    ->where("a.oid=$oid")
	    ->find();

		$twhere['status'] = "freebuyOrderNotice";
		$templatemsg = $TemplateModel->where($twhere)->find();
		$templateId = $templatemsg['templateId'];
		
		$data['first'] = array('value'=> '亲爱的'.$order["nickname"].'，您参加的“由你定价”活动，已经成功完成目标！','color'=>"#743A3A");
		$data['keyword1'] = array('value'=> $detail["pnames"],'color'=>'#173177');
		$data['keyword2'] = array('value'=> $detail["amount"],'color'=>'#173177');
		$data['keyword3'] = array('value'=> "发货中",'color'=>'#173177');
		$data['remark'] = array('value'=> '接下来，我们会安排人员尽快发货，订单号：'.$order["serialNumber"],"color"=>'#008000');

		$toUser = $order["fromUserName"];
		$template_id = $templateId;
		$url = C("SERVER_HOST") . "call.html?customerId=" . $cid .
			"&module=freebuy&method=getView&params=%7B%22oid%22%3A%22$oid%22%7D";
		 $url = urlencode($url);
		$topcolor = "#FF0000";
		//data得转json
		WeixinApi::sendTpl($toUser, $template_id, $url,$topcolor,$data);

	}
	/**
	 * [removeOrderRefue 取消关注删除助力的1元]
	 * @param  [type] $param [description]
	 * @return [type]        [description]
	 */
	public function removeOrderRefue($param){
		$customerId = Session::$user['customerId'];
		$WeixinUserModel=M("_user_weixin_info");
	    Session::switchCustomer(0);
		$OrderModel=M("module_product_order");
		$RecordModel=M("module_freebuy_record");
		Session::switchCustomer($customerId);
		$message=$param->message;
		$fromUserName=$message->fromUserName;
		$oid=$param->id;
		$refu=C("BASEMONEY");
		$record=$RecordModel->where("fromUserName='$fromUserName'")->find();
		if($record) {
			$oid=$record["oid"];
			$id=$record["id"];
			$order=$OrderModel->where("id=$oid")->find();
			if($order["status"]!="paypart"){
				return;
			}
			$OrderModel->startTrans();
			$updateOrderStatus=$OrderModel->where("id=$oid")->setDec("refueMoney",$refu);
			if($updateOrderStatus===false) {
				Log::write("取消关注订单失败结果".$OrderModel->getlastsql().$updateOrderStatus);
			}
			$updateRecordStatus=$RecordModel->where("id=$id")->setField("deleted",1);
			if($updateRecordStatus===false) {
				Log::write("取消关注失败结果".$RecordModel->getlastsql().$updateOrderStatus);
			}
			if($updateOrderStatus!==false && $updateRecordStatus!==false) {
				$OrderModel->commit();
			} else {
				Log::write("失败回滚".$OrderModel->getlastsql().$RecordModel->getlastsql());
				$OrderModel->rollback();
			}
		}
	}
	public function getRule($param){
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $oid=$param->oid;
	    $retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $oid=$param->oid;
	    Session::switchCustomer(0);
	    $OrderModel = M("module_product_order");
		$DetailModel = M("module_product_order_detail");
		$RecordModel=M("module_freebuy_record");	
		Session::switchCustomer($customerId);

		$result=$OrderModel->alias("a")
		->join("wx_".$customerId."_user_weixin_info b on a.fromUserName=b.openid")
		->field("a.*,b.nickname,b.headimgurl")
		->where("a.id=$oid")->find();

		$productList=$DetailModel->alias("a")
		->join("inner join wx_module_product b on a.pid=b.id")
		->field("b.name,b.picUrl,b.freeBuyMoney")
		->where("a.oid=$oid")
		->find();
		$Guid = new Guid();
		$guid = $Guid->toString();
		$result['guid']=$guid;
		$result["productList"]=$productList;

		$result["oid"]=$oid;

    	Output::instance()->module('freebuy',"rule")->object($result);
	}
}